package com.ruoyi.link.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <P> @Author: SongKeCheng
 * <P> Type: Class
 * <P> Description:
 * <P> Date: 2024/12/30:11:41
 */

@SuppressWarnings({"unchecked", ""})
@RestController
@CrossOrigin
@RequestMapping("/link")
public class LinkController implements InitializingBean {
    private static final Logger log = LoggerFactory.getLogger(LinkController.class);


    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
    @Autowired
    private  RestTemplate restTemplate;

    /**
     * 设置编码，解决中文乱码问题
    */
    public void setRestTemplateEncode(RestTemplate restTemplate) {
        if (null == restTemplate || ObjectUtils.isEmpty(restTemplate.getMessageConverters())) {
            return;
        }
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        for (int i = 0; i < messageConverters.size(); i++) {
            HttpMessageConverter<?> httpMessageConverter = messageConverters.get(i);
            if (httpMessageConverter.getClass().equals(StringHttpMessageConverter.class)) {
                messageConverters.set(i, new StringHttpMessageConverter(StandardCharsets.UTF_8));
            }
        }
    }


    @GetMapping("/proxy")
    public String proxyRequest(@RequestParam(defaultValue = "https://www.baidu.com") String url) {
        try {
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            return response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return "Error fetching data from www.baidu.com";
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        setRestTemplateEncode(restTemplate);
    }
}
